import React from 'react'
import { useRef } from 'react'
import { Button, Form, Input } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { useSelector } from 'react-redux'

// import styles from './index.module.less'
import axios from '@/utils/http'
import { upload_imgs } from '@/utils/index'
import { select_active_two } from '@/redux/slice/subject'
import MyUpload from './upload'

const SubjectDetial: React.FC = () => {
    const active_file: any = useRef({})
    const two_obj: any = useSelector(select_active_two)
    //获取组件的实例
    const [form] = Form.useForm()

    const file_change = (file_info: any) => {
        //1 useState可以,但是我这个不用在页面触发更新。所以使用useRef
        // console.log('file_info', file_info)
        active_file.current = file_info
    }
    //点击保存按钮,看必填项是否填了.填了就打印form_data
    const submit_click = async () => {
        const form_data = await form.validateFields()
        if (form_data) {
            if (active_file.current?.fileList?.length) {
                //图片上传
                //有file对象 =>想得到 cdn地址

                const imgs_url_arr = await upload_imgs(active_file.current.fileList)
                console.log('imgs_url_arr', imgs_url_arr)
                form_data.img = imgs_url_arr
            }
            form_data.two_id = two_obj.value
            // console.log('form_data img', form_data)
        }
        await axios.post('/api/topic', form_data)
        //清空form表单的信息
        form.resetFields()
    }
    return (
        <Form
            name='basic'
            labelCol={{ span: 2 }}
            style={{ width: 800 }}
            wrapperCol={{ span: 16 }}
            form={form} //获取组件的实例
            autoComplete='off' //自动完成
            className=''
        >
            <Form.Item>
                <h2>题目详情</h2>
            </Form.Item>
            <Form.Item label='题目' name='title' rules={[{ required: true, message: '请输入' }]}>
                <Input placeholder='React中受控组件和非受控组件?' />
            </Form.Item>
            <Form.Item label='描述' name='dec' rules={[{ required: true, message: '请输入' }]}>
                <TextArea placeholder='与state绑定就是受控组件.不绑定就是非受控组件' />
            </Form.Item>
            <MyUpload change={file_change} />
            <Button type='primary' style={{ marginTop: 20 }} onClick={submit_click}>
                保存
            </Button>
        </Form>
    )
}

export default SubjectDetial
